package com.example.coding_problem.Fragment;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.coding_problem.Broken_line_diagram;
import com.example.coding_problem.R;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static android.support.constraint.Constraints.TAG;

public class LineChart1 extends Fragment {
    private LineChart broken_listl;
    private LineDataSet set1;
    private int i=0;
    private ArrayList<Entry>pointValues=new ArrayList<>();
    private List<Broken_line_diagram>bld=new ArrayList<>();
    public LineChart1(){
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.line_chart1, container, false);
        initline(view);
        initChart();
        initSQL();
        return view;
    }
    private void initSQL() {
        SQLiteDatabase db=getActivity().openOrCreateDatabase("EnvironmentalLndicators", getActivity().MODE_PRIVATE, null);
        Cursor infol=db.query("info",null, null,null, null, null, null, null);
        int i=0;
        if (infol!=null){
            while (infol.moveToNext()){
                Broken_line_diagram data=new Broken_line_diagram();
                i++;
                data.setId(i+"");
                data.setHumidity(infol.getString(infol.getColumnIndex("Humidity")));
                data.setIllumination(infol.getString(infol.getColumnIndex("Illumination")));
                data.setCQ2(infol.getString(infol.getColumnIndex("CQ2")));
                data.setPm(infol.getString(infol.getColumnIndex("pm")));
                data.setRoad_condition(infol.getString(infol.getColumnIndex("Road_condition")));
                data.setTemperature(infol.getString(infol.getColumnIndex("Temperature")));
                bld.add(data);
            }
        }
    }
    private void initline(View view){
        broken_listl =view.findViewById(R.id.broken_line);
        //坐标点对象 构造函数 第一个参数为x点坐标 第二个为y点
        ArrayList<Entry> values1 = new ArrayList<>();
        set1 = new LineDataSet(values1, "温度");
        //设置折线颜色
        set1.setColor(Color.parseColor("#6950a1"));
        set1.setValueTextSize(10);
        //设置折线图的数据
        setLineChartData(broken_listl,set1);
        set1.setValueTextSize(10f);
    }
    private void initChart() {
        broken_listl.animateXY(1000, 1000);
        //=========================设置图例=========================
        // 像"□ xxx"就是图例
        Legend legend = broken_listl.getLegend();
        //设置图例显示在chart那个位置 setPosition建议放弃使用了
        //设置垂直方向上还是下或中
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        //设置水平方向是左边还是右边或中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        //设置所有图例位置排序方向
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //设置图例的形状 有圆形、正方形、线
        legend.setForm(Legend.LegendForm.CIRCLE);
        //是否支持自动换行 目前只支持BelowChartLeft, BelowChartRight, BelowChartCenter
        legend.setWordWrapEnabled(true);
        //=======================设置X轴显示效果==================
        XAxis xAxis = broken_listl.getXAxis();
        //是否启用X轴
        xAxis.setEnabled(false);
        //是否绘制X轴线
        xAxis.setDrawAxisLine(false);
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(false);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(false);
        //设置X轴显示位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置竖线为虚线样式
        // xAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴标签数
        xAxis.setLabelCount(5, true);
        //图表第一个和最后一个label数据不超出左边和右边的Y轴
        // xAxis.setAvoidFirstLastClipping(true);
        //设置限制线 12代表某个该轴某个值，也就是要画到该轴某个值上
        LimitLine limitLine = new LimitLine(12);
        //设置限制线的宽
        limitLine.setLineWidth(1f);
        //设置限制线的颜色
        limitLine.setLineColor(Color.RED);
        //设置基线的位置
        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        limitLine.setLabel("马丹我是基线，也可以叫我水位线");
        //设置限制线为虚线
        limitLine.enableDashedLine(10f, 10f, 0f);
        //=================设置左边Y轴===============
        YAxis axisLeft = broken_listl.getAxisLeft();
        //是否启用左边Y轴
        axisLeft.setEnabled(true);
        //设置最小值（这里就按demo里固死的写）
        axisLeft.setAxisMinimum(0);
        //设置最大值（这里就按demo里固死的写了）
        axisLeft.setAxisMaximum(50);
        //设置横向的线为虚线
        axisLeft.enableGridDashedLine(10f, 10f, 0f);
        //axisLeft.setDrawLimitLinesBehindData(true);
        //====================设置右边的Y轴===============
        YAxis axisRight = broken_listl.getAxisRight();
        //是否启用右边Y轴
        axisRight.setEnabled(false);
        //设置最小值（这里按demo里的数据固死写了）
        axisRight.setAxisMinimum(1);
        //设置最大值（这里按demo里的数据固死写了）
        axisRight.setAxisMaximum(20);
        //设置横向的线为虚线
        axisRight.enableGridDashedLine(10f, 10f, 0f);
    }
    //设置折线图数据
    public void setLineChartData(final LineChart broken_line, final LineDataSet set1 ){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        RequestBody requestBody = (RequestBody) retrofit.create(Environmental_indicators.BlogService.class);
        Environmental_indicators.BlogService service = retrofit.create(Environmental_indicators.BlogService.class);
        Call<ResponseBody> call = service.getBlog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Gson gson1 = new Gson();
                    Broken_line_diagram carlist=gson1.fromJson(response.body().string(),Broken_line_diagram.class);
                    i++;
                    //获取折线图数据
                    set1.setValues(pointValues);
                    LineData data=new LineData(set1);
                    broken_line.setData(data); //设置数据
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "run"+pointValues);
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}
